package my.jwds.p564;

public class NearestPalindromic {

    public static void main(String[] args) {

        NearestPalindromic obj = new NearestPalindromic();
        System.out.println(obj.nearestPalindromic("9999999"));
    }

    public String nearestPalindromic(String n) {
        int point = (n.length()-1)/2;
        boolean copyPoint = n.length()% 2 == 0;
        long nlong = Long.valueOf(n);
        long prefix = nlong / (long) (Math.pow(10,n.length() - 1 - point));
        long now = generic(prefix,copyPoint);
        long min = generic(prefix-1,copyPoint);
        long max = generic(prefix+1,copyPoint);
        long l1 = (long) Math.pow(10,n.length()-1)-1;
        long l2 = (long) Math.pow(10,n.length())+1;
        long [] longs = {now,min,max,l1,l2};
        long minRes = Long.MAX_VALUE, minDiff = Long.MAX_VALUE;
        for (long l : longs) {
            long diff = Math.abs(l - nlong);
            if (l != nlong &&(diff < minDiff || diff == minDiff && l < minRes)){
                minRes = l;
                minDiff = diff;
            }
        }
        return minRes+"";

    }


    private long generic(long prefix,boolean copyPoint){
        if (prefix <0)return 0;
        StringBuilder sb= new StringBuilder(prefix+"");
        String res;
        if (copyPoint){
            res = sb.toString()+sb.reverse().toString();
        }else{
            res = sb.toString()+sb.deleteCharAt(sb.length()-1).reverse().toString();
        }
        if (res.length() > 19)return 0;
        return Long.valueOf(res);
    }
}